package tgc.edu.ljc.web.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import tgc.edu.ljc.custom.AjaxResult;
import tgc.edu.ljc.custom.CommonController;
import tgc.edu.ljc.entity.Customer;
import tgc.edu.ljc.entity.SysRole;
import tgc.edu.ljc.entity.SysUser;
import tgc.edu.ljc.security.UserUtils;
import tgc.edu.ljc.service.CustomerService;
import tgc.edu.ljc.service.SysRoleService;
import tgc.edu.ljc.service.SysUserService;
import tgc.edu.ljc.web.form.CustomerForm;

@Controller
@RequestMapping(value = "/customer")
public class CustomerController extends CommonController<Customer, Integer, CustomerForm> {

	@Autowired
	private CustomerService service;
	@Autowired
	private SysRoleService sysRoleService;
	@Autowired
	private SysUserService sysUserService;
	@Autowired
	private UserUtils userUtils;
	
	@Override
	public void edit(CustomerForm form, ModelMap map) throws InstantiationException, IllegalAccessException {
		List<SysRole> roles = sysRoleService.findByParentIsNull();
		map.put("roles", roles);
		super.edit(form, map);
	}

	@Override
	public Object save(CustomerForm form) {
		BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
		try {
			Customer model = new Customer();
			Integer id = form.getId();
			if (id != null) {
				model = service.findById(id);
			}
			String password = form.getPassword();
			if (StringUtils.hasText(password)) {
				password = encoder.encode(password);
				model.setPassword(password);
			}
			if (!StringUtils.hasText(model.getPassword())) {
				model.setPassword(encoder.encode("123456"));
			}
			BeanUtils.copyProperties(form, model, "id", "password");

			List<SysRole> roles = new ArrayList<>();
			for (String code : form.getRoles().split(",")) {
				roles.add(sysRoleService.findbyCode(code));
			}
			model.setRoles(roles);
			service.save(model);
			return new AjaxResult("OK");
		} catch (Exception e) {
			return new AjaxResult(false, "数据保存失败");
		}

	}

	@Override
	public Specification<Customer> buildSpec(CustomerForm form) {
		Specification<Customer> specification = new Specification<Customer>() {

			private static final long serialVersionUID = 1L;

			@Override
			public Predicate toPredicate(Root<Customer> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
				HashSet<Predicate> rules = new HashSet<>();
				String name = form.getName();
				if (StringUtils.hasText(name)) {
					rules.add(cb.equal(root.get("name"), name));
				}
				String username = form.getUsername();
				if (StringUtils.hasText(username)) {
					rules.add(cb.equal(root.get("username"), username));
				}
				return cb.and(rules.toArray(new Predicate[rules.size()]));
			}

		};
		return specification;

	}

	/***
	 * 用户名验证（防重复）
	 * 
	 * @param username
	 * @return
	 */
	@RequestMapping(value = "/yanz")
	@ResponseBody
	public Object userNameYanz(String username) {
		Map<String, Object> map = new HashMap<>();
		SysUser sysUser = sysUserService.findByUsername(username);
		if (sysUser == null) {
			map.put("valid", true);
		} else {
			map.put("valid", false);
		}

		return map;
	}
	/***
	 * 密码验证（修改密码时）
	 * 
	 * @param username
	 * @return
	 */
	@RequestMapping(value = "/pyanz")
	@ResponseBody
	public Object PasswordYanz(String password) {
		Map<String, Object> map = new HashMap<>();
		SysUser user = userUtils.getUser();
		BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
			boolean f = encoder.matches(password, user.getPassword());
			if (f) {
				map.put("valid", true);
			} else {
				map.put("valid", false);
			}
		
		return map;
	}
	/***
	 * 修改密码
	 * @param username
	 * @return
	 */
	@RequestMapping(value = "/pedit")
	@ResponseBody
	public Object PasswordEdit(String password,String xpassword,String qrpassword) {
		SysUser user = userUtils.getUser();
		BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
		boolean f = encoder.matches(password, user.getPassword());
		if (f) {
			if(xpassword.equals(qrpassword)) {
				user.setPassword(encoder.encode(qrpassword));
				sysUserService.save(user);
				return new AjaxResult(true,"数据保存成功");
			}else {
				return new AjaxResult(true,"数据保存失败");
			}
		} else {
			return new AjaxResult(false,"数据保存失败");
		}
	}
	
	/***
	 * 密码重置
	 * @param id  用户ID
	 * @return
	 */
	@RequestMapping(value="/restPwd")
	@ResponseBody
	public Object restPwd(Integer id) {
		SysUser user = sysUserService.findById(id);
		BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
		String password = encoder.encode("123456");
		user.setPassword(password);
		sysUserService.save(user);
		return new AjaxResult("密码复位成功");
	}

}
